const express = require("express");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const fs = require("fs");
const path = require("path");
const _ = require('lodash');
const router = express.Router();
const usersFile = path.join(__dirname, "../../data/users.json");
const SECRET_KEY = "mockserver_secret"; // 🔒 生产环境应使用环境变量

// 读取用户数据
const getUsers = () => {
    if (!fs.existsSync(usersFile)) return [];
    return JSON.parse(fs.readFileSync(usersFile));
};

// 注册用户
router.post("/register", async (req, res) => {
    const { username, password } = req.body;
    if (!username || !password) return res.status(400).json({ message: "用户名和密码必填" });

    let users = getUsers();
    if (_.find(users,user => user.username === username)) {
        return res.status(400).json({ message: "用户名已存在" });
    }

    const hashedPassword = await bcrypt.hash(password, 10);
    users.push({ username, password: hashedPassword });
    fs.writeFileSync(usersFile, JSON.stringify(users, null, 2));
    res.json({ success: true, message: "注册成功" });
});

// 登录用户
router.post("/login", async (req, res) => {
    const { username, password } = req.body;
    let users = getUsers();
    const user = _.find(users, user => user.username === username);

    if (!user || !(await bcrypt.compare(password, user.password))) {
        return res.status(401).json({ message: "用户名或密码错误" });
    }

    const token = jwt.sign({ username }, SECRET_KEY, { expiresIn: "2h" });
    res.cookie('token', token, { httpOnly: true, secure: true, sameSite: 'Strict' });
    res.json({ success: true, token });
});

// 鉴权中间件
const authenticate = (req, res, next) => {
    const token = req.headers.authorization?.split(" ")[1];
    if (!token) return res.status(401).json({ message: "未授权" });

    jwt.verify(token, SECRET_KEY, (err, decoded) => {
        if (err) return res.status(403).json({ message: "Token无效" });
        req.user = decoded;
        next();
    });
};

module.exports = { authRouter: router, authenticate };